﻿/* ============================================================================
(c) Copyright 2012 Hewlett-Packard Development Company, L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge,publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================ */
using System;
using System.Collections.Generic;
using HPCloud.Objects.Utility;
using System.Net.Http;
using HPCloud.Objects.Domain.Compute.Security;
using HPCloud.Objects.Domain.Compute;

namespace HPCloud.Objects.DataAccess.Compute
{
    public class SecurityRepository : BaseRepository, ISecurityRepository
    {
        public SecurityRepository(RepositoryContext context) : base(context)   { }

        #region Security Group Operations
//==================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="group"></param>
//==================================================================================================
        public SecurityGroup SaveSecurityGroup(NewSecurityGroup group)
        {
            string absoluteURI                      = this.Context.ServiceDescription.Url + "/os-security-groups";
            ObjectContent<NewSecurityGroup> content = new ObjectContent<NewSecurityGroup>(group, this.CreateFormatter());
          
            return this.InvokeEndpoint<SecurityGroup>(absoluteURI, content);
        }
//==================================================================================================
/// <summary>
/// 
/// </summary>
//==================================================================================================
        public void DeleteSecurityGroup(string securityGroupId)
        {
            string absoluteURI = this.Context.ServiceDescription.Url + "/os-security-groups/" + securityGroupId;
            this.InvokeEndpoint(HttpMethod.Delete, absoluteURI, null, null);
        }
//==================================================================================================
/// <summary>
/// 
/// </summary>
/// <returns></returns>
//==================================================================================================
        List<Domain.Compute.Security.SecurityGroup> ISecurityRepository.GetSecurityGroups()
        {
            string absoluteURI            = this.Context.ServiceDescription.Url + "/os-security-groups";
            SecurityGroups securityGroups = this.InvokeEndpoint<SecurityGroups>(HttpMethod.Get, absoluteURI, null, null);
            List<SecurityGroup> groups    = new List<SecurityGroup>();

            foreach (SecurityGroup group in securityGroups.List) {
                groups.Add(group);
            }

            return groups;
        }
//==================================================================================================
/// <summary>
/// 
/// </summary>
/// <returns></returns>
//==================================================================================================
        SecurityGroup ISecurityRepository.GetSecurityGroup(string securityGroupId)
        {
            string absoluteURI = this.Context.ServiceDescription.Url + "/os-security-groups/" + securityGroupId;
            try
            {
                return this.InvokeEndpoint<SecurityGroup>(HttpMethod.Get, absoluteURI, null, null);
            }
            catch (Exception ex)
            {               
                return null;
            }
        }
        #endregion
        #region Security Rule Operations
//==================================================================================================
/// <summary>
/// 
// add-rule -ipr "iprTest" -IP "tcp" -tp "95" -fp "91" -gid "2302"
/// </summary>
/// <param name="rule"></param>
//==================================================================================================
        public SecurityGroupRule SaveSecurityRule(NewSecurityRule rule)
        {
            string absoluteURI                     = this.Context.ServiceDescription.Url + "/os-security-group-rules";
            ObjectContent<NewSecurityRule> content = new ObjectContent<NewSecurityRule>(rule, this.CreateFormatter());

            return this.InvokeEndpoint<SecurityGroupRule>(absoluteURI, content);
        }
//==================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="securityGroupRuleId"></param>
//==================================================================================================
        public void DeleteSecurityRule(string securityGroupRuleId)
        {
            string absoluteURI = this.Context.ServiceDescription.Url + "/os-security-group-rules/" + securityGroupRuleId;
            this.InvokeEndpoint(HttpMethod.Delete, absoluteURI, null, null);
        }
        #endregion
        #region Key Pair Operations
//==================================================================================================
/// <summary>
/// 
/// </summary>
//==================================================================================================
        public List<KeyPair> GetKeyPairs()
        {
            string absoluteURI = this.Context.ServiceDescription.Url + "/os-keypairs";
            this.MediaType     = DataAccess.MediaType.json;
            RootClass IPs      = this.InvokeEndpoint<RootClass>(HttpMethod.Get, absoluteURI, null, null);
            this.MediaType     = DataAccess.MediaType.xml;

            List<KeyPair> keypairs = new System.Collections.Generic.List<KeyPair>();
            for (int i = 0; i < IPs.keypairs.Length; i++) {
                keypairs.Add(IPs.keypairs[i].keypair);
            }

            return keypairs;           
        }
//==================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="keypair"></param>
//==================================================================================================
        public KeyPair SaveKeyPair(NewKeyPair keypair)
        {
            string absoluteURI                = this.Context.ServiceDescription.Url + "/os-keypairs";
            ObjectContent content = new ObjectContent<NewKeyPair>(keypair, this.CreateFormatter());
            content.Headers.Add("Charset", "utf-8");
            KeyPairResult result =  this.InvokeEndpoint<KeyPairResult>(absoluteURI, content);

            // Epic hack....
            
            KeyPair kp     = new KeyPair();
            kp.Fingerprint = result.Fingerprint;
            kp.Name        = result.Name;
            kp.PrivateKey  = result.PrivateKey;
            kp.PublicKey   = result.PublicKey;
            kp.UserId      = result.UserId;

            return kp;
        }
//==================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="keypairName"></param>
//==================================================================================================
        public void DeleteKeyPair(string keypairName)
        {
            string absoluteURI = this.Context.ServiceDescription.Url + "/os-keypairs/" + keypairName;
            this.InvokeEndpoint(HttpMethod.Delete, absoluteURI, null, null);
        }
//==================================================================================================
/// <summary>
/// 
/// </summary>
/// <returns></returns>
//==================================================================================================
        Limits ISecurityRepository.GetLimits()
        {
            this.MediaType = DataAccess.MediaType.json;
            string absoluteURI = this.Context.ServiceDescription.Url + "/limits";
            return this.InvokeEndpoint<Limits>(HttpMethod.Get, absoluteURI, null, null);
        }
        #endregion

    }
}